import { defineStore } from "pinia";
import * as userController from "@/apis/user/UserController";
import { reactive, ref } from "vue";
import { UnfoldLessFilled } from "@vicons/material";

export const useUserStore = defineStore("user", () => {
	//定义分页参数格式
	const formData = reactive({
		pageIndex: 1,
		pageSize: 10,
		userName: "",
		mobilePhone: "",
	});

	// const status = ref()
	// const token = ref('')

	//定义分页返回结果格式
	const pageRes = reactive({
		code: "",
		message: "",
		data: {
			dataList: [],
			total: 0,
		},
	});
	//定义返回结果格式
	const res = reactive({
		code: "",
		message: "",
		data: {},
	});
	//定义存储库 -> 获取分页数据
	const toUserPage = async (data) => {
		const response = await userController.userPage(data);
		pageRes.code = response.code;
		pageRes.message = response.message;
		pageRes.data = response.data;
	};

	//定义存储库 -> 获取行数据
	const toGetUser = async (data) => {
		const response = await userController.getUser(data);
		res.code = response.code;
		res.message = response.message;
		res.data = response.data;
	};
	//定义存储库 -> 新增数据
	const toAddUser = async (data) => {
		const response = await userController.addUser(data);
		res.code = response.code;
		res.message = response.message;
		res.data = response.data;
	};
	//定义存储库 -> 修改行数据
	const toUpdateUser = async (data) => {
		const response = await userController.updateUser(data);
		res.code = response.code;
		res.message = response.message;
		res.data = response.data;
	};

	//定义存储库 -> 删除行数据
	const toDeleteUser = async (data) => {
		const response = await userController.deleteUser(data);
		res.code = response.code;
		res.message = response.message;
		res.data = response.data;
	};
	//定义存储库 -> 导出列表数据
	const toExportUser = async (data) => {
		try {
			const response = await userController.exportUser(data);

			let blob = undefined;
			if (response instanceof Blob) {
				blob = response;
			} else {
				blob = new Blob([response.data], { type: "application/vnd.ms-excel" });
			}
			//创建下载链接并触发下载
			const downloadUrl = window.URL.createObjectURL(blob);
			const link = document.createElement("a");
			link.href = downloadUrl;
			link.download = "用户数据.xlsx"; //下载文件的名称
			document.body.appendChild(link);
			link.click();

			//清理临时的下载链接
			window.URL.revokeObjectURL(downloadUrl);
			document.body.removeChild(link);

			res.code = response.code;
			res.message = response.message;
			res.data = response.data;
		} catch (error) {
			console.error("导出失败:", error);
			throw error; // 处理错误
		}
	};
	return {
		formData,
		pageRes,
		res,
		toUserPage,
		toGetUser,
		toUpdateUser,
		toDeleteUser,
		toAddUser,
		toExportUser,
	};
});
